package com.yipingnai.blog.controller.admin;

import com.yipingnai.blog.model.RespBean;
import com.yipingnai.blog.model.User;
import com.yipingnai.blog.service.UserService;
import com.yipingnai.blog.utils.MD5Util;
import com.yipingnai.blog.utils.VerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author: jiangym
 * @Date: 2020/5/18 15:28
 */
@RestController
public class LoginController {

    @Autowired
    UserService userService;
    @PostMapping("/admin/login")
    public RespBean login(String username, String password, HttpServletRequest request){
        if(null == username || "".equals(username) || null == password || "".equals(password)){
            return RespBean.error("信息错误，请重新输入");
        }
        password = MD5Util.md5(password);
        User user = userService.login(username,password);
        if(user != null){
            request.getSession().setAttribute("user",user);
            return RespBean.ok("登录成功",user);
        }
        return RespBean.error("登录失败，请检查账号密码");
    }



    @GetMapping("/verifyCode")
    public void getVerifyCode(HttpSession session, HttpServletResponse resp) throws IOException {
        VerificationCode code = new VerificationCode();
        BufferedImage image = code.getImage();
        String text = code.getText();
        session.setAttribute("verify_code",text);
        VerificationCode.output(image,resp.getOutputStream());
    }
}
